package com.bryant.miantong.ui.home

import android.app.ActivityOptions
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.print.PrintAttributes.Margins
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2

import com.bryant.bryant_weather.base.BaseBindingFragment
import com.bryant.miantong.BannerAdapter
import com.bryant.miantong.R
import com.bryant.miantong.databinding.FragmentHomeBinding
import com.bryant.miantong.ui.login.LoginActivity
import com.bryant.miantong.utils.MMKVManager


class HomeFragment : BaseBindingFragment<FragmentHomeBinding>() {
    private lateinit var viewPager2: ViewPager2
    private lateinit var adapter: BannerAdapter
    private lateinit var indicatorContainer: ViewGroup
    private val handler = Handler(Looper.getMainLooper())
    private var currentPosition = 0

    // 轮播图片地址（实际项目中替换为你的图片URL或资源ID）
    private val bannerImages = listOf(
        R.mipmap.banner_ai,
        R.mipmap.banner_qa,
        R.mipmap.banner_pj,
    )


    override fun initBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, parent, false)
    }

    override fun initView() {
        // 点击去登陆按钮，实现登录页跳转
        binding.loginButton.setOnClickListener {
            // 检查是否已经登录
            if (MMKVManager.isLoggedIn()) {
                // 已登录则不跳转到登录页
                Toast.makeText(requireContext(), "您已登录", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 未登录则跳转到登录页面
            val intent = Intent(requireContext(), LoginActivity::class.java)
            val options = ActivityOptions.makeCustomAnimation(
                requireContext(),
                R.anim.slide_right_in,
                R.anim.slide_left_out
            )
            ContextCompat.startActivity(requireContext(), intent, options.toBundle())
        }
    }


    /* override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewPager2 = binding.viewPager222
        indicatorContainer = binding.indicatorContainer
        adapter = BannerAdapter(bannerImages)
        viewPager2.adapter = adapter
        // 初始化指示器
        initIndicators()
        // 设置初始位置（保证向左滑动也能循环）
        val initialPosition = Int.MAX_VALUE / 2 - (Int.MAX_VALUE / 2 % bannerImages.size)
        viewPager2.currentItem = initialPosition
        currentPosition = initialPosition

        // 监听页面切换，更新指示器
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPosition = position
                updateIndicators()
            }
        })
    }*/
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        // 初始化控件（从view中获取，而非Activity）
//        viewPager2 =binding.viewPager222
//        indicatorContainer = binding.indicatorContainer
//
//        // 初始化适配器（上下文用requireContext()）
//        adapter = BannerAdapter(bannerImages)
//        viewPager2.adapter = adapter
//
//        // 初始化指示器
//        initIndicators()
//
//        // 设置初始位置
//        val initialPosition = Int.MAX_VALUE / 2 - (Int.MAX_VALUE / 2 % bannerImages.size)
//        viewPager2.currentItem = initialPosition
//        currentPosition = initialPosition
//
//        // 页面切换监听（使用viewLifecycleOwner避免内存泄漏）
//        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
//            override fun onPageSelected(position: Int) {
//                super.onPageSelected(position)
//                currentPosition = position
//                updateIndicators()
//            }
//        })
//        // 设置合适的padding值
//        viewPager2.setPadding(10.dp, 0, 10.dp, 0)
//        viewPager2.clipToPadding = false
//    }
   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)
       // 初始化控件（从view中获取，而非Activity）
       viewPager2 = binding.viewPager222
       indicatorContainer = binding.indicatorContainer

       // 初始化适配器（上下文用requireContext()）
       adapter = BannerAdapter(bannerImages)
       viewPager2.adapter = adapter

       // 初始化指示器
       initIndicators()

       // 设置初始位置
       val initialPosition = Int.MAX_VALUE / 2 - (Int.MAX_VALUE / 2 % bannerImages.size)
       viewPager2.currentItem = initialPosition
       currentPosition = initialPosition

       // 页面切换监听（使用viewLifecycleOwner避免内存泄漏）
       viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
           override fun onPageSelected(position: Int) {
               super.onPageSelected(position)
               currentPosition = position
               updateIndicators()
           }
       })
       // 设置合适的padding值
       viewPager2.setPadding(10.dp, 0, 10.dp, 0)
       viewPager2.clipToPadding = false


   }

    // ================================== 轮播图相关 ==================================
    // 自动轮播任务
    private val autoScrollTask = object : Runnable {
        override fun run() {
            currentPosition++
            viewPager2.currentItem = currentPosition
            handler.postDelayed(this, 3000) // 3秒轮播一次
        }
    }

    // dp转px工具方法
    private val Int.dp: Int
        get() = (this * resources.displayMetrics.density + 0.5f).toInt()

    // 初始化指示器（小圆点）
    private fun initIndicators() {
        indicatorContainer.removeAllViews()
        for (i in bannerImages.indices) {
            val indicator = ImageView(context).apply {
                layoutParams = ViewGroup.MarginLayoutParams(8.dp, 8.dp).apply {
                    setMargins(4.dp, 0, 4.dp, 0) // 左右间距4dp
                }
                setImageResource(R.drawable.indicator_selector)
                isSelected = i == 0 // 默认选中第一个
            }
            indicatorContainer.addView(indicator)
        }
    }

    // 更新指示器状态
    private fun updateIndicators() {
        val realPosition = currentPosition % bannerImages.size
        for (i in bannerImages.indices) {
            indicatorContainer.getChildAt(i).isSelected = i == realPosition
        }
    }

    // 开始自动轮播
    override fun onResume() {
        super.onResume()
        handler.postDelayed(autoScrollTask, 3000)
    }

    // 停止自动轮播
    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(autoScrollTask)
    }

}